import APIZPZ from "../../utils/apiZpz"

// pages/search/search.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1, // 页码
    pageNumMax: 2,
    modelName: '',
    searchTime: 0,
    modelList: <any>[],
    oldTime: 0,
    history: <any>[],
    nullTipVisible: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.setData({
      history: wx.getStorageSync('searchHistory')||[]
    })
  },
  modelNameChange(e: any) {
    console.log(e.detail)
    clearTimeout(this.data.searchTime);
    this.setData({
      pageNum: 1, // 页码
      pageNumMax: 2,
      modelList: [],
      modelName: e.detail,
      nullTipVisible: false,
    })
    if (!e.detail) {
      return;
    }
    this.data.searchTime = setTimeout(() => {
      this.search();
    }, 500);
  },
  search() {
    if (this.data.pageNum > this.data.pageNumMax) {
      return;
    }
    APIZPZ.fuzzyModelSearch(this.data.pageNum, this.data.modelName).then((res: any) => {
      this.setData({
        nullTipVisible: true,
        pageNumMax: res.data.pages,
        modelList: [...this.data.modelList, ...res.data.list]
      })
    })
  },
  loadNextPage() {
    this.setData({
      pageNum: ++this.data.pageNum
    })
    this.search();
  },
  toEvaluate(e: any) {
    const data = e.currentTarget.dataset.model;
    const time = new Date().getTime();
    if (time - this.data.oldTime < 1000) {
      return;
    }
    this.data.oldTime = time;
    APIZPZ.getModelEvaluate(data.id).then(() => {
      if (!this.data.history.some((item: any) => item.id === data.id)) {
        if (this.data.history.length === 10) {
          this.data.history.pop();
        }
        wx.setStorageSync('searchHistory', [data, ...this.data.history]);
      }
      wx.redirectTo({
        url: `/pages/evaluate/model-evaluate/model-evaluate?id=${data.id}`
      });
    });
  },
  clearSearchHistory() {
    wx.setStorageSync('searchHistory', []);
    wx.showToast({
      title: '清除成功',
      icon: 'none',
      duration: 2000
    });
    this.setData({
      history: wx.getStorageSync('searchHistory')
    })
  },
  cancel() {
    wx.navigateBack({ delta: 1 })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})